using Microsoft.AspNetCore.Mvc;
using RuoVea.ExDto;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service;

[ApiExplorerSettings(GroupName = "TradeFlow")]
public partial class JxGoodsService : IApplicationService
{
    /// <summary>
    /// 商品仓储
    /// </summary>
    private readonly SugarRepository<JxGoods> _goodsRepository;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="goodsRepository"></param>
    /// <param name="currentUser"></param>
    public JxGoodsService(SugarRepository<JxGoods> goodsRepository, ICurrentUser currentUser)
    {
        _goodsRepository = goodsRepository;
        _currentUser = currentUser;
    }

//    public Task<PagingResult<InventoryInfo>> QueryInventoriesAsync(Database db, PagingCriteria criteria)
//    {
//        var sql = @"select a.* 
//     ,0 as ImportQty
//     ,0 as ImportReturnQty
//     ,0 as ExportQty
//     ,0 as ExportReturnQty
//     ,0 as InventoryQty
//from JxGoods a 
//where a.CompNo=@CompNo";
//        return db.QueryPageAsync<InventoryInfo>(sql, criteria);
//    }

    /// <summary>
    /// 查询商品分页列表
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<JxGoods>>> GetPagesAsync(JxGoodsPageParam? data)
    {
        var restful = new RestfulResult<PageResult<JxGoods>>() { Code = CodeStatus.OK };
        data ??= new JxGoodsPageParam { PageNo = 1, PageSize = 10 };
        
        var query = _goodsRepository.AsQueryable().Where(u => u.Creator == _currentUser.UserId);
        
        // 添加查询条件
        if (!string.IsNullOrEmpty(data.Code))
            query = query.Where(u => u.Code.Contains(data.Code));
        if (!string.IsNullOrEmpty(data.Name))
            query = query.Where(u => u.Name.Contains(data.Name));
        if (!string.IsNullOrEmpty(data.Category))
            query = query.Where(u => u.Category.Contains(data.Category));
        if (!string.IsNullOrEmpty(data.Model))
            query = query.Where(u => u.Model.Contains(data.Model));
        
        var result = await query.ToPageAsync(data.PageNo, data.PageSize);
        restful.Data = result;
        return restful;
    }

    /// <summary>
    /// 获取所有商品列表
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<JxGoods>>> GetListAsync()
    {
        var restful = new RestfulResult<PageResult<JxGoods>>() { Code = CodeStatus.OK };
        PageParam data = new PageParam { PageNo = 1, PageSize = 1000 };
        
        var query = await _goodsRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .OrderByDescending(u => u.Id)
            .ToPageAsync(data.PageNo, data.PageSize);
        
        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 添加商品
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task<RestfulResult> AddAsync(JxGoods data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        
        // 检查编码是否重复
        var isExist = await _goodsRepository.IsAnyAsync(u => u.Code == data.Code && u.Creator == _currentUser.UserId);
        if (isExist)
        {
            restful.Message = i18n.data_duplicate;
            return restful;
        }
        
        data.Creator = _currentUser.UserId;
        bool result = await _goodsRepository.InsertAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.add}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 更新商品
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> UpdateAsync(JxGoods data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        
        var goods = await _goodsRepository.GetByIdAsync(data.Id);
        if (goods == null || goods.Creator != _currentUser.UserId)
        {
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }
        
        // 检查编码是否重复（排除当前记录）
        var isExist = await _goodsRepository.IsAnyAsync(u => u.Code == data.Code && u.Id != data.Id && u.Creator == _currentUser.UserId);
        if (isExist)
        {
            restful.Message = i18n.data_duplicate;
            return restful;
        }
        
        bool result = await _goodsRepository.UpdateAsync(data, true, true, $"{i18n.modify}");
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.modify}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 删除商品
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        
        if (data.Id == 0)
        {
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
        
        // 检查是否存在且属于当前用户
        var goods = await _goodsRepository.GetByIdAsync(data.Id);
        if (goods == null || goods.Creator != _currentUser.UserId)
        {
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }
        
        bool isDelete = await _goodsRepository.DeleteByIdAsync(data.Id);
        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.success}";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
    }


    //public Task<PagingResult<GoodsInfo>> QueryGoodsesAsync(PagingCriteria criteria)
    //{
    //    return Database.Query<JxGoods>(criteria).ToPageAsync<GoodsInfo>();
    //}

    //public Task<List<GoodsInfo>> GetGoodsesAsync()
    //{
    //    return Database.Query<JxGoods>().Where(d => d.CompNo == CurrentUser.CompNo).ToListAsync<GoodsInfo>();
    //}

    //public async Task<Result> DeleteGoodsesAsync(List<GoodsInfo> infos)
    //{
    //    if (infos == null || infos.Count == 0)
    //        return Result.Error(Language.SelectOneAtLeast);

    //    var database = Database;
    //    var oldFiles = new List<string>();
    //    var result = await database.TransactionAsync(Language.Delete, async db =>
    //    {
    //        foreach (var item in infos)
    //        {
    //            await db.DeleteFilesAsync(item.Id, oldFiles);
    //            await db.DeleteAsync<JxGoods>(item.Id);
    //        }
    //    });
    //    if (result.IsValid)
    //        AttachFile.DeleteFiles(oldFiles);
    //    return result;
    //}

    //public async Task<Result> SaveGoodsAsync(UploadInfo<GoodsInfo> info)
    //{
    //    var database = Database;
    //    var model = await database.QueryByIdAsync<JxGoods>(info.Model.Id);
    //    model ??= new JxGoods();
    //    model.FillModel(info.Model);

    //    var vr = model.Validate(Context);
    //    if (vr.IsValid)
    //    {
    //        if (await database.ExistsAsync<JxGoods>(d => d.Id != model.Id && d.Code == model.Code))
    //            vr.AddError($"商品[{model.Code}]已存在！");
    //    }
    //    if (!vr.IsValid)
    //        return vr;

    //    var fileFiles = info.Files?.GetAttachFiles(nameof(JxGoods.Files), "GoodsFiles");
    //    return await database.TransactionAsync(Language.Save, async db =>
    //    {
    //        await db.AddFilesAsync(fileFiles, model.Id, key => model.Files = key);
    //        await db.SaveAsync(model);
    //        info.Model.Id = model.Id;
    //    }, info.Model);
    //}
}